<template>
  <div>
    <el-card :body-style="{ padding: '15px' }">
      <div style="display: flex; flex-wrap: wrap">
        <div class="grid mt-2">
          <div class="flex items-center">
            <div class="options-label">开始时间</div>
            <div class="block">
              <el-date-picker
                v-model="alarmAskData.start_time"
                @change="alarmAskData.end_time = ''"
                type="datetime"
                placeholder="请选择开始时间"
                style="width: 310px"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
          </div>
        </div>
        <div class="grid mt-2">
          <div class="flex items-center">
            <div class="options-label">截止时间</div>
            <div class="block">
              <el-date-picker
                v-model="alarmAskData.end_time"
                type="datetime"
                placeholder="请选择结束时间"
                style="width: 310px"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledEndDate"
              />
            </div>
          </div>
        </div>
        <div class="grid mt-2">
          <div class="flex items-center">
            <div class="options-label">事件类型</div>
            <div class="block">
              <el-select
                v-model="alarmAskData.event_type"
                clearable
                style="width: 310px"
              >
                <el-option
                  v-for="item in optionsType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div class="grid mt-2">
          <div class="flex items-center">
            <div class="options-label">事件设备</div>
            <div class="block">
              <el-select
                v-model="topics"
                style="width: 310px"
                multiple
                clearable
                popper-class="custom-header"
                placeholder="请选择设备"
              >
                <div class="check_Box">
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="indeterminate"
                    @change="handleCheckAll"
                  >
                    全部选项
                  </el-checkbox>
                </div>
                <el-option
                  v-for="item in cameraOptions"
                  :key="item.device_id"
                  :label="item.device_id"
                  :value="item.device_id"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div class="grid mt-2">
          <div class="flex items-center">
            <div class="flex items-center">
              <div class="options-label">处理结果</div>
              <div class="block">
                <el-select
                  v-model="alarmAskData.status"
                  clearable
                  style="width: 310px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
        </div>
        <div class="grid mt-2">
          <div style="line-height: 50px">
            <el-button type="primary" style="width: 60px" @click="getAlarmData"
              >检索</el-button
            >
            <el-button
              style="width: 60px"
              @click="
                resetData();
                getAlarmData();
              "
              >重置</el-button
            >
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="mt-5" :body-style="{ padding: '15px' }">
      <div class="flex justify-between">
        <div class="text-sm" style="line-height: 32px">
          <div>
            检索结果：共<span class="text-rose-500"> {{ total }} </span>条记录
          </div>
        </div>
        <div>
          <el-button plain @click="getDataByTime(1, 'hours')"
            >最近1小时</el-button
          >
          <el-button plain @click="getDataByTime(24, 'hours')"
            >最近1天</el-button
          >
          <el-button plain @click="getDataByTime(3, 'days')">最近3天</el-button>
          <el-button plain @click="getDataByTime(7, 'days')">最近7天</el-button>
          <el-button plain @click="dialogVisible = true">批量处理</el-button>
        </div>
      </div>
      <el-divider />
      <div class="alarm">
        <el-card
          class="alarmCard"
          :body-style="{ padding: '0px' }"
          v-for="(item, i) in alarmList"
          :key="item.id"
          @click="openPopUps(i)"
        >
          <el-image class="w-full h-[180px]" :src="item.image" fit="fill" />
          <div style="padding: 5px 13px 5px 10px; font-size: 15px">
            <div class="flex justify-between relative">
              <div>事件类型：{{ item.event_type }}</div>
              <div class="state_unresolved" v-if="item.status === 1">
                待处理
              </div>
              <div
                class="state_processed bg-[#79bbff]"
                v-if="item.status === 2"
              >
                正报
              </div>
              <div
                class="state_processed bg-[#e6a23c]"
                v-if="item.status === 3"
              >
                误报
              </div>
            </div>
            <div class="mb-1">
              <div>事件时间：{{ item.updated_at }}</div>
            </div>
            <div class="mb-1">
              <div>事件地点：{{ item.location }}</div>
            </div>
            <div class="mb-1">
              <div>事件设备：{{ item.device_id }}</div>
            </div>
            <div class="mb-1">
              <div>事件备注：{{ item.remark }}</div>
            </div>
          </div>
        </el-card>
      </div>
      <div style="display: flex; justify-content: space-between">
        <div />
        <el-pagination
          v-model:current-page="alarmAskData.page"
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="getAlarmData"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      @close="closeBatchAlarm"
      width="20%"
      top="30vh"
    >
      <template #header="{ titleId, titleClass }">
        <div class="flex items-center">
          <h4 :id="titleId" :class="titleClass">一键确认告警</h4>
        </div>
      </template>
      <div class="ml-2">您将对所有告警记录一键确认,请选择确认信息:</div>
      <div class="flex mt-3 items-center">
        <div class="ml-2 text-base">处理结果：</div>
        <el-select
          v-model="batchesState"
          clearable
          placeholder="请选择处理结果"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="flex justify-between">
        <div />
        <div class="mt-[15px]">
          <el-button @click="closeBatchAlarm">取消</el-button>
          <el-button type="primary" @click="batchesSolve"> 确定 </el-button>
        </div>
      </div>
    </el-dialog>
    <pop-ups
      @close="close"
      @nextPageFn="nextPageFn"
      @solvingAlarm="solvingAlarm"
      :alarmList="alarmList"
      :index="index"
      ref="popUpsData"
      v-if="popUpsFlag"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import popUps from "./components/popUps.vue";
import { getAlarmList, dealWithAlarm } from "@/api/alarm";
import { getCameraList } from "@/api/camera";
import type { CheckboxValueType } from "element-plus";
import { ElMessage } from "element-plus";
import moment from "moment";
const popUpsData = ref<any>();
const dialogVisible = ref<boolean>(false);
const batchesState = ref<string>("");
const index = ref<number>(0);
const total = ref<number>(0);
const alarmList = ref<any[]>([]);
const indeterminate = ref(false);
const popUpsFlag = ref<any>(false);
const checkAll = ref(false);
const topics = ref<CheckboxValueType[]>([]);
const cameraOptions = ref<any[]>([]);
const alarmAskData = ref<any>({
  start_time: "",
  end_time: "",
  device_id: [],
  event_type: "",
  status: "",
  page: 1,
  page_size: 10
});

onMounted(() => {
  getAlarmData();
  getCameraOptions();
});

const getDataByTime = (time, type) => {
  const startTime = moment().subtract(time, type).format("YYYY-MM-DD HH:mm:ss");
  const entTime = moment().format("YYYY-MM-DD HH:mm:ss");
  alarmAskData.value.start_time = startTime;
  alarmAskData.value.end_time = entTime;
  getAlarmData();
  resetData();
};

const nextPageFn = (val: string | null) => {
  if (val) {
    nextPage();
  } else {
    previousPage();
  }
};

const nextPage = async () => {
  if (index.value < alarmList.value.length - 1) {
    index.value += 1;
    await popUpsDataChange();
  } else {
    if (alarmAskData.value.page < Math.ceil(total.value / 10)) {
      alarmAskData.value.page++;
      index.value = 0;
      await getAlarmData();
      await popUpsDataChange();
    } else {
      ElMessage({
        message: "已到最后一条！",
        type: "warning"
      });
    }
  }
};

const previousPage = async () => {
  if (index.value > 0) {
    index.value--;
    await popUpsDataChange();
  } else {
    if (alarmAskData.value.page > 1) {
      alarmAskData.value.page--;
      index.value = 9;
      await getAlarmData();
      await popUpsDataChange();
    } else {
      ElMessage({
        message: "已到第一条！",
        type: "warning"
      });
    }
  }
};

const popUpsDataChange = () => {
  alarmList.value[index.value].status === 1
    ? (popUpsData.value.processResult = "")
    : (popUpsData.value.processResult = alarmList.value[index.value].status);
  popUpsData.value.remark = alarmList.value[index.value].remark;
  popUpsData.value.imgUrl = [alarmList.value[index.value].image];
};

const solvingAlarm = async () => {
  if (popUpsData.value.processResult) {
    const id = alarmList.value[index.value].id;
    const status = Number(popUpsData.value.processResult);
    const res = await dealWithAlarm({
      id,
      status,
      remark: popUpsData.value.remark
    });
    if (res.code === 0) {
      alarmList.value[index.value].remark = popUpsData.value.remark;
      alarmList.value[index.value].status = popUpsData.value.processResult;
      ElMessage({
        message: alarmList.value[index.value].device_id + "告警信息编辑成功",
        type: "success"
      });
    }
  } else {
    ElMessage.error("未选择处理结果");
  }
};

const batchesSolve = async () => {
  if (batchesState.value) {
    const res = await dealWithAlarm({
      id: 0,
      status: batchesState.value
    });
    if (res.code === 0) {
      ElMessage({
        message: "批量处理告警成功",
        type: "success"
      });
      getAlarmData();
      closeBatchAlarm();
    } else {
      ElMessage.error("处理失败");
    }
  } else {
    ElMessage.error("未选择处理结果");
  }
};

const resetData = () => {
  alarmAskData.value = {
    start_time: "",
    end_time: "",
    device_id: [],
    event_type: "",
    status: "",
    page: 1,
    page_size: 10
  };
};

const openPopUps = (i: number) => {
  popUpsFlag.value = true;
  index.value = i;
};

const close = () => {
  popUpsFlag.value = false;
};

const closeBatchAlarm = () => {
  dialogVisible.value = false;
  batchesState.value = "";
  console.log(123);
};

const getAlarmData = async () => {
  const params = parameterChanges();
  const res = await getAlarmList(params);
  total.value = res.result.total;
  alarmList.value = res.result.items;
};

const getCameraOptions = async () => {
  const res = await getCameraList({ page: 1, page_size: 10000 });
  cameraOptions.value = res.result.items;
};

const disabledEndDate = time => {
  if (!alarmAskData.value.start_time) {
    return false;
  }
  return time.getTime() < new Date(alarmAskData.value.start_time).getTime();
};

const options = [
  {
    value: 1,
    label: "待处理"
  },
  {
    value: 2,
    label: "正报"
  },
  {
    value: 3,
    label: "误报"
  }
];
const optionsType = [
  {
    value: "0",
    label: "人员玩手机"
  },
  {
    value: "1",
    label: "区域入侵"
  },
  {
    value: "2",
    label: "火灾监测"
  }
];

const options1 = [
  {
    value: 2,
    label: "正报"
  },
  {
    value: 3,
    label: "误报"
  }
];

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false;
  if (val) {
    topics.value = cameraOptions.value.map(_ => _.device_id);
  } else {
    topics.value = [];
  }
};

const parameterChanges = () => {
  const url = [];
  for (const key in alarmAskData.value) {
    if (Array.isArray(alarmAskData.value[key])) {
      alarmAskData.value[key].forEach(item => {
        url.push(`${key}=${encodeURI(item)}`);
      });
    } else {
      url.push(`${key}=${encodeURI(alarmAskData.value[key])}`);
    }
  }
  return url.join("&");
};

watch(topics, val => {
  alarmAskData.value.device_id = topics.value;
  if (val.length === 0) {
    checkAll.value = false;
    indeterminate.value = false;
  } else if (val.length === optionsType.length) {
    checkAll.value = true;
    indeterminate.value = false;
  } else {
    indeterminate.value = true;
  }
});
</script>
<style scoped lang="scss">
.grid {
  min-width: 411px;
}

.options-label {
  min-width: 57px;
  margin-right: 15px;
  font-size: 14px;
}

.alarm {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
}

.alarmCard {
  box-sizing: border-box;
  flex-basis: calc(20% - 16px);
  height: 340px;
  margin: 0 8px 17px;
  cursor: pointer;
}

.alarmCard:hover {
  transform: scale(1.03);
}

.state_unresolved {
  position: absolute;
  top: -5px;
  right: 0;
  width: 65px;
  height: 30px;
  line-height: 30px;
  color: #f56c6c;
  text-align: center;
  background-color: #fef0f0;
  border: 1px solid #fdd;
  border-radius: 5px;
}

.state_processed {
  position: absolute;
  top: -5px;
  right: 0;
  width: 65px;
  height: 30px;
  line-height: 30px;
  color: #fff;
  text-align: center;
  border-radius: 5px;
}

.el-divider--horizontal {
  margin: 15px 0;
}

.check_Box {
  display: flex;
  align-items: center;
  height: 30px;
  padding: 0 0 0 10px;
  line-height: 30px;
  border-bottom: 1px solid #dcdfe6;
}

::v-deep .el-dialog__body {
  padding: 10px;
}
</style>
